<template>
    <div ref="chartContainer" />
</template>

<script lang="ts" setup>
    import {
        shallowRef,
        watch,
        defineProps,
        PropType,
        onMounted,
        onBeforeUnmount,
    } from 'vue';
    import * as echarts from 'echarts';

    const props = defineProps({
        option: {
            type: Object as PropType<any>,
            default: undefined,
        },
        optionOpt: {
            type: Object,
            default: () => ({}),
        },
        loading: {
            type: Boolean,
            default: false,
        },
        loadingOption: {
            type: Object,
            default: undefined,
        },
    });
    const chartContainer = shallowRef();
    const chart: any = shallowRef();
    function draw(container: HTMLElement) {
        const echartsInstance = echarts.init(container);
        echartsInstance.setOption(props.option);
        chart.value = echartsInstance;
    }

    function setOption(option: any) {
        // eslint-disable-next-line no-unused-expressions
        chart.value && chart.value.setOption(option, props.optionOpt);
    }

    function getChart() {
        return chart.value;
    }

    watch(
        () => props.option,
        () => {
            setOption(props.option);
        },
        { immediate: true }
    );
    watch(
        () => [chart.value, props.loading],
        ([instance, loading]) => {
            if (instance) {
                // eslint-disable-next-line no-unused-expressions
                loading
                    ? instance.showLoading(props.loadingOption)
                    : instance.hideLoading();
            }
        },
        { immediate: true }
    );
    defineExpose({
        getChart,
        setOption,
    });
    let chartObserver: ResizeObserver | null;
    onBeforeUnmount(() => {
        chartObserver?.disconnect();
        chartObserver = null;
    });
    onMounted(() => {
        draw(chartContainer.value);
        chartObserver = new ResizeObserver(() => {
            chart.value.resize();
        });
        chartObserver.observe(chartContainer.value);
    });
</script>

<style lang="less" scoped></style>
